package com.subaiqiao.yunshiyuan.entrance.ysy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.subaiqiao.yunshiyuan.basis.utils.Result;
import com.subaiqiao.yunshiyuan.entrance.ysy.pojo.Favorite;
import com.subaiqiao.yunshiyuan.entrance.ysy.pojo.Product;
import com.subaiqiao.yunshiyuan.entrance.ysy.pojo.UserInfo;
import com.subaiqiao.yunshiyuan.entrance.ysy.service.FavoriteService;
import com.subaiqiao.yunshiyuan.entrance.ysy.service.ProductService;
import com.subaiqiao.yunshiyuan.entrance.ysy.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 曹朝禹
 * @since 2022-05-13
 */
@RestController
@RequestMapping("/ysy/favorite")
@Api( tags = "收藏夹与浏览历史")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ProductService productService;

    @ApiOperation("分页查询商品收藏列表")
    @GetMapping("/FindFavoritesPage.do")
    public Result FindFavoritesPage(HttpServletRequest request,
                                    @RequestParam @ApiParam("页码") Integer pageNum,
                                    @RequestParam @ApiParam("数量") Integer pageSize){
        String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_type", 1)
                .eq("is_buy",0)
                .eq("status",0)
                .eq("username", user.getUsername());
        IPage<Favorite> page = new Page<>(pageNum, pageSize);
        return Result.success(favoriteService.page(page, wrapper));
    }

    @ApiOperation("添加商品到收藏")
    @PostMapping("/collection.do")
    public Result Collection(HttpServletRequest request, @RequestParam @ApiParam("商品编号") String ProductBar){
        String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        QueryWrapper<Product> wrapper_product = new QueryWrapper<>();
        wrapper_product.eq("product_bar",ProductBar);
        Product product = productService.getOne(wrapper_product);
        if(product!=null) {
            Favorite favorite = new Favorite();
            favorite.setUsername(user.getUsername());
            favorite.setFavoriteType(1);
            favorite.setProductBar(ProductBar);
            favorite.setIsBuy(0);
            favorite.setStatus(0);
            favoriteService.save(favorite);
            return Result.success(favoriteService.save(favorite));
        }else{
            return Result.error("未查询到商品信息");
        }
    }

    @ApiOperation("查询商品是否在收藏夹中")
    @GetMapping("/FindProductInFavorites.do")
    public Result FindProductInFavorites(HttpServletRequest request,
                                    @RequestParam @ApiParam("商品编号") String ProductBar){
        String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername())
                .eq("is_buy",0)
                .eq("status",0)
                .eq("favorite_type", 1)
                .eq("product_bar", ProductBar);
        Favorite favorite = favoriteService.getOne(wrapper);
        if(favorite==null){
            return Result.error("商品不在收藏夹中");
        }else{
            return Result.success("已收藏该商品");
        }
    }

    @ApiOperation("商品取消收藏")
    @PostMapping("/CancelCollection.do")
    public Result CancelCollection(HttpServletRequest request,
                                   @RequestParam @ApiParam("商品编号") String ProductBar,
                                   @RequestParam @ApiParam("修改状态(0购买 1删除)") Integer status){
        String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        QueryWrapper<Favorite> wrapper_favorite = new QueryWrapper<>();
        wrapper_favorite.eq("product_bar",ProductBar)
                .eq("username", user.getUsername())
                .eq("is_buy",0)
                .eq("status",0)
                .eq("favorite_type", 1)
                .orderByDesc("update_datetime");
        Favorite favorite = favoriteService.getOne(wrapper_favorite);
        if(favorite!=null) {
            if(status==0){
                favorite.setIsBuy(1);
                return Result.success(favoriteService.updateById(favorite));
            }else if(status ==1){
                favorite.setStatus(1);
                return Result.success(favoriteService.removeById(favorite));
            }else{
                return Result.error("状态输入错误");
            }
        }else{
            return Result.error("未查询到收藏信息");
        }
    }


    @ApiOperation("分页查询商品浏览历史")
    @GetMapping("/FindhistoryPage.do")
    public Result FindhistoryPage(HttpServletRequest request){
            String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        if(user==null){
            return Result.error("登录信息有误");
        }
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("favorite_type", 0)
                .eq("username", user.getUsername())
                .orderByDesc("create_datetime");
        List<Favorite> favoriteList = favoriteService.list(wrapper);
        List<Map<String, List<Favorite>>> o = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i=0;i<favoriteList.size();i++){
            String date = sdf.format(favoriteList.get(i).getCreateDatetime());
            if(o.size()==0){
                List<Favorite> favorites = new ArrayList<>();
                favorites.add(favoriteList.get(i));
                Map<String, List<Favorite>> map = new HashMap<>();
                map.put(date,favorites);
                o.add(map);
            }
            for (Map<String, List<Favorite>> item: o) {
                if(item.containsKey(sdf.format(favoriteList.get(i).getCreateDatetime()))){
                    //存在
                    List<Favorite> map_temp = item.get(date);
                    boolean flag = false;
                    for (Favorite f:map_temp) {
                        if(f.getProductBar().equals(favoriteList.get(i).getProductBar())){
                            flag = true;
                        }
                    }
                    if(!flag){
                        map_temp.add(favoriteList.get(i));
                        item.replace(date, map_temp);
                    }
                }else{
                    //不存在
                    List<Favorite> favorites = new ArrayList<>();
                    favorites.add(favoriteList.get(i));
                    item.put(date,favorites);
                }
            }
        }
        return Result.success(o);
    }



}
